/***************************************************
 @Name :        小铭同学
 @Time :        2025-09-03
 @Email :       LiaoMingWJ233@163.com
 @Comment :     温湿度 设备驱动
 @FileName :    hal_tem_hum.c
 @Version :     1.0
****************************************************/


#include "hal_tem_hum.h"

int tem_hum_init()
{
    return 0;
}

double tem_collect()
{
    int temp_raw = 0;
    int temp_offset = 0;
    float temp_scale = 0;

    tem_hum_read_int(READ_TEM_HUM_DERIVCE, READ_TEM_RAW, &temp_raw);
    tem_hum_read_int(READ_TEM_HUM_DERIVCE, READ_TEM_OFFSET, &temp_offset);
    tem_hum_read_float(READ_TEM_HUM_DERIVCE, READ_TEM_SCALE, &temp_scale);

    double temperature = (temp_raw + temp_offset) * temp_scale / 1000;

    return temperature;
}

float hum_collect()
{
    int hum_raw = 0;
    int hum_offset = 0;
    float hum_scale = 0;

    tem_hum_read_int(READ_TEM_HUM_DERIVCE, READ_HUM_RAW, &hum_raw);
    tem_hum_read_int(READ_TEM_HUM_DERIVCE, READ_HUM_OFFSET, &hum_offset);
    tem_hum_read_float(READ_TEM_HUM_DERIVCE, READ_HUM_SCALE, &hum_scale);

    double humidity = (hum_raw + hum_offset) * hum_scale / 1000;

    return humidity;
}

int tem_hum_read_int(const char *device, const char *filename, int *val)
{
    int ret = 0;
    FILE *sysfsfp;
    char temp[128];

    memset(temp, '0', 128);

    ret = sprintf(temp, READ_TEM_HUM_TEMP, device, filename);
    if (ret < 0)
        goto error;

    sysfsfp = fopen(temp, "r");

    if (!sysfsfp)
    {
        ret = -errno;
        goto error;
    }

    errno = 0;

    if (fscanf(sysfsfp, "%d\n", val) != 1)
    {
        ret = errno ? -errno : -ENODATA;
        if (fclose(sysfsfp))
            perror("read_sysfs_float(): Failed to close dir");

        goto error;
    }

    if (fclose(sysfsfp))
        ret = -errno;

error:

    return ret;
}

int tem_hum_read_float(const char *device, const char *filename, float *val)
{
    int ret = 0;
    FILE *sysfsfp;
    char temp[128];

    memset(temp, '0', 128);

    ret = sprintf(temp, READ_TEM_HUM_TEMP, device, filename);
    if (ret < 0)
        goto error;

    sysfsfp = fopen(temp, "r");

    if (!sysfsfp)
    {
        ret = -errno;
        goto error;
    }

    errno = 0;

    if (fscanf(sysfsfp, "%f\n", val) != 1)
    {
        ret = errno ? -errno : -ENODATA;
        if (fclose(sysfsfp))
            perror("read_sysfs_float(): Failed to close dir");

        goto error;
    }

    if (fclose(sysfsfp))
        ret = -errno;

error:

    return ret;
}

int tem_hum_close()
{
    return 0;
}
